package com.zym.init.configuration;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.zym.init.exception.BannedException;
import com.zym.init.service.UserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 通用配置
 *
 * @author ZouYangMing
 */
@Configuration
public class ResourcesConfiguration implements WebMvcConfigurer {

    private final UserService userService;

    public ResourcesConfiguration(UserService userService) {
        this.userService = userService;
    }

    /**
     * Sa-Token 拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 的路由拦截器
        registry.addInterceptor(new SaInterceptor(handle -> {
            // 允许匿名 排除多个路径
            SaRouter.notMatch("/user/isLogin", "/swagger-ui/**", "/api-docs", "/favicon.ico").check(r -> StpUtil.checkLogin());
            // 检查账号是否已被封禁
            SaRouter.match(StpUtil.isLogin()).check(r -> {
                boolean isBanned = userService.checkUserIsBanned(StpUtil.getLoginIdAsLong());
                if (isBanned) {
                    // 踢出登录
                    StpUtil.logout();
                    // 抛出异常
                    throw new BannedException();
                }
            });
        })).addPathPatterns("/**").excludePathPatterns("/user/doLogin");
    }

    /**
     * 跨域配置
     */
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 设置访问源地址
        config.addAllowedOriginPattern("*");
        // 设置访问源请求头
        config.addAllowedHeader("*");
        // 设置访问源请求方法
        config.addAllowedMethod("*");
        // 有效期 1800秒
        config.setMaxAge(1800L);
        // 添加映射路径，拦截一切请求
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        // 返回新的CorsFilter
        return new CorsFilter(source);
    }

}
